define(["angular",
    "framework/utils/JSONPrettyFormat",
    'framework/dataGrid/DataGridModule',
    'framework/pagination/GillionPaginationModule',
    'framework/msg/GillionMsgModule'
], function (angular, JSONPrettyFormat) {
    /**
     *  Module
     *
     * Description
     */
    var RuleModule = angular.module('RuleModule', ['DataGridModule',
        'GillionPaginationModule',
        'GillionMsgModule'
    ]);
    RuleModule.controller('RuleController', function ($scope, Resource, $dataSourceManager, GillionMsg, $location,$compile, $timeout) {
        $scope.id="2222222222";

        $scope.businessModelId="6176947849096339456";
        $scope.context = "{\"oper\":\"&&\",\"left\":{\"oper\":\"<\",\"left\":{\"oper\":\"*\",\"left\":{\"type\":\"parenthesis\",\"expression\":{\"oper\":\"+\",\"left\":{\"type\":\"const\",\"value\":\"2\"},\"right\":{\"type\":\"const\",\"value\":\"3\"}}},\"right\":{\"type\":\"const\",\"value\":\"6\"}},\"right\":{\"type\":\"const\",\"value\":\"10\"}},\"right\":{\"oper\":\"<\",\"left\":{\"type\":\"const\",\"value\":\"5\"},\"right\":{\"type\":\"const\",\"value\":\"4\"}}}";
        $scope.count=1;
        $scope.countCondition=1;
        //     $scope.curSymbol = 1;
        $scope.nowClick = 1;
        $scope.jsonContext={};
        $scope.showSign=false;
        $scope.showProperty=false;
        $scope.showEntry=false;
        $scope.showNone=true;
        $scope.showAllCondition=false;
        $scope.showMethod=false;
        $timeout(function () {
            ruleResource.get({"id":$scope.id},function(response){
                $scope.context = response.expression;

                var json = eval('(' + $scope.context + ')');

                var conditionList=showRule(json.if.condition);
                setHtml(conditionList,'condition');
                var thenList =showThen(json.if.then);
                setHtml(thenList,'then');
            });
        });
        function showThen(list){
            var thenList=[];
            for(var i=0;i<list.length;i++){
                if(list[i].type=="setRtnValue"){
                    thenList  =thenList.concat({'type':'setRtnValue'});
                    thenList = thenList.concat(showRule(list[i].value));
                }else if(list[i].type=="setVariable"){
                    thenList =thenList.concat({'type':'setVariable','key':list[i].key});
                    thenList = thenList.concat(showRule(list[i].value));
                }
            }
            return thenList;
        }

        function showRule(json){
            var resultList=[];
            if(json.type=="parenthesis"){
                resultList = resultList.concat({'oper':'('});
                resultList = resultList.concat(showRule(json.expression));
                resultList = resultList.concat({'oper':')'});
            }else {
                if (json.left != null || json.right != null) {
                    resultList = resultList.concat(showRule(json.left));
                    resultList = resultList.concat({'oper':json.oper});
                    resultList = resultList.concat(showRule(json.right));
                } else {
                    resultList.push(json);
                }
            }
            return resultList;
        }

        function setHtml(list,type) {
            if (type == 'condition'){
                if (list.length > 0) {
                    var count = $scope.count++;
                    angular.element("#condition").append(
                        $compile(
                            "<div class='entry-set' name='rowC' id='remove" + count + "'>" +
                            "<div class='entry-set-l' id='addRow" + count + "'>" +
                            "</div>" +
                            "<div class='entry-set-r'>" +
                            "<span><a href ng-click='addCondition(" + count + ")'>()</a></span>" +
                            "<span><a href ng-click='removeCondition()' ng-dblclick='removeRowCondition(" + count + ")'>&nbsp;-</a></span>" +
                            "</div>" +
                            "</div>"
                        )($scope)
                    )
                }
            }
            for(var i=0;i<list.length;i++){
                if(list[i].oper!="undefined"&&list[i].oper!=null&&list[i].oper!="&&"&&list[i].oper!="||") {
                    angular.element("#addRow" + count).append(
                        $compile(
                            "<span  id='click"+$scope.countCondition+"'><a href='#' name='node'  id='node"+$scope.nowClick+"'  ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;)'  ng-dblclick='addFront(&apos;"+$scope.nowClick+"&apos;)'    value='"+JSON.stringify(list[i])+"'>"+list[i].oper+"</a></span>"
                        )($scope)
                    );
                    $scope.nowClick++;
                    $scope.countCondition++;
                }else if(list[i].type=="model"||list[i].type=="const"){
                    angular.element("#addRow" + count).append(
                        $compile(
                            "<span  id='click"+$scope.countCondition+"'><a href='#' name='node' id='node"+$scope.nowClick+"' ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;)'  ng-dblclick='addFront(&apos;"+$scope.nowClick+"&apos;)'   value='"+JSON.stringify(list[i])+"'>"+list[i].value+"</a></span>"
                        )($scope)
                    );
                    $scope.nowClick++;
                    $scope.countCondition++;
                }else if(list[i].type=="variable"){
                    angular.element("#addRow" + count).append(
                        $compile(
                            "<span  id='click"+$scope.countCondition+"'><a href='#' name='node' id='node"+$scope.nowClick+"' ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;)'  ng-dblclick='addFront(&apos;"+$scope.nowClick+"&apos;)'   value='"+JSON.stringify(list[i])+"'>"+list[i].variableName+"</a></span>"
                        )($scope)
                    );
                    $scope.nowClick++;
                    $scope.countCondition++;
                }else if(list[i].type=="nowDate"){
                    angular.element("#addRow" + count).append(
                        $compile(
                            "<span  id='click"+$scope.countCondition+"'><a href='#' name='node' id='node"+$scope.nowClick+"' ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;)'  ng-dblclick='addFront(&apos;"+$scope.nowClick+"&apos;)'   value='"+JSON.stringify(list[i])+"'>当前时间</a></span>"
                        )($scope)
                    );
                    $scope.nowClick++;
                    $scope.countCondition++;
                }else if(list[i].type=="lastDateTime"){
                    list[i].source
                    angular.element("#addRow" + count).append(
                        $compile(
                            "<span  id='click"+$scope.countCondition+++"'><a href='#' name='node' id='node"+$scope.nowClick+"' ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;)'  ng-dblclick='addFront(&apos;"+$scope.nowClick+++"&apos;)'   value='"+JSON.stringify(list[i].source)+"'>"+list[i].source.value+"</a></span>"+
                            "<span  id='click"+$scope.countCondition+"'><a href='#' name='node' id='node"+$scope.nowClick+"' ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;)'  ng-dblclick='addFront(&apos;"+$scope.nowClick+"&apos;)'   value='"+JSON.stringify(list[i])+"'>当天最后时间</a></span>"
                        )($scope)
                    );
                    $scope.nowClick++;
                    $scope.countCondition++;
                }else if(list[i].oper=="&&"){
                    count = $scope.count++;
                    angular.element("#condition").append(
                        $compile(
                            "<div class='entry-set' name='rowC' id='remove" + count + "'>" +
                            "<div class='entry-set-l' id='addRow" + count + "'>" +
                            "<span class='also'><a href='#' ng-click='change("+count+")' name='node'  id='symbol"+count+"' value='{&apos;oper&apos;:&apos;&&&apos;}'>并且</a></span>"+
                            "</div>" +
                            "<div class='entry-set-r'>" +
                            "<span><a href ng-click='addCondition(" + count + ")'>()</a></span>" +
                            "<span><a href ng-click='removeCondition()' ng-dblclick='removeRowCondition(" + count + ")'>&nbsp;-</a></span>" +
                            "</div>" +
                            "</div>"
                        )($scope)
                    )
                }else if(list[i].oper=="||"){
                    count = $scope.count++;
                    angular.element("#condition").append(
                        $compile(
                            "<div class='entry-set' name='rowC' id='remove" + count + "'>" +
                            "<div class='entry-set-l' id='addRow" + count + "'>" +
                            "<span class='also'><a href='#' ng-click='change("+count+")' name='node'  id='symbol"+count+"' value='{&apos;oper&apos;:&apos;||&apos;}'>或者</a></span>"+
                            "</div>" +
                            "<div class='entry-set-r'>" +
                            "<span><a href ng-click='addCondition(" + count + ")'>()</a></span>" +
                            "<span><a href ng-click='removeCondition()' ng-dblclick='removeRowCondition(" + count + ")'>&nbsp;-</a></span>" +
                            "</div>" +
                            "</div>"
                        )($scope)
                    )
                }else if(list[i].type=="setRtnValue"){
                    count = $scope.count++;
                    angular.element("#then").append(
                        $compile(
                            "<div class='entry-set' name='rowC' id='remove" + count + "'>" +
                            "<div class='entry-set-l' id='addRow" + count + "'>" +
                            "<span class='also'><a href='#' name='node' id  = 'then"+count+"' ng-click='changeThen("+count+")' value='{&apos;type&apos;:&apos;setRtnValue&apos;}' >返回：</a></span>"+
                            "</div>"+
                            "<div class='entry-set-r'>"+
                            "<span><a href ng-click='addCondition(" + count + ")'>()</a></span>" +
                            "<span><a href ng-click='removeCondition()' ng-dblclick='removeRowCondition(" + count + ")'>&nbsp;-</a></span>" +
                            "</div>"+
                            "</div>"
                        )($scope)
                    );
                }else if(list[i].type=="setVariable"){
                    count = $scope.count++;
                    angular.element("#then").append(
                        $compile(
                            "<div class='entry-set' name='rowC' id='remove" + count + "'>" +
                            "<div class='entry-set-l' id='addRow" + count + "'>" +
                            "<span class='also'><a href='#' name='node' id  = 'then"+count+"' ng-click='changeThen("+count+")' value='{&apos;type&apos;:&apos;setVariable&apos;}' >临时变量：</a></span>"+
                            "<span  id='click"+$scope.countCondition+"'><a href='#' name='node' id='node"+$scope.nowClick+"' ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;)'  ng-dblclick='addFront(&apos;"+$scope.nowClick+"&apos;)'   value='"+JSON.stringify(list[i].key)+"'>KEY:"+list[i].key+"</a></span>"+
                            "</div>"+
                            "<div class='entry-set-r'>"+
                            "<span><a href ng-click='addCondition(" + count + ")'>()</a></span>" +
                            "<span><a href ng-click='removeCondition()' ng-dblclick='removeRowCondition(" + count + ")'>&nbsp;-</a></span>" +
                            "</div>"+
                            "</div>"
                        )($scope)
                    );
                    $scope.nowClick++;
                    $scope.countCondition++;
                }
            }
        }
        var childAttributeResource = Resource("/grule-manager/businessModelAttribute/childList/:id", {
            id: "@id"
        });
        var ruleResource = Resource("/grule-manager/rule/:id", {
            id: "@id"
        });
        //加载模型
        Resource("/grule-manager/businessModelAttribute/list/:id", {id: '@id'}).get({
            id:  $scope.businessModelId
        }, function (response) {
            if(response.data!=null){
                $scope.modelAttributes=response.data;
            }
        });
        //加载变量
        Resource("/grule-manager/variables/assembly/:id", {id: '@id'}).get({
            id:  $scope.id
        }, function (response) {
            if(response.data!=null){
                $scope.variables=response.data;
            }
        });
        function init(){
            if( document.getElementById("node" + $scope.nowClick)!=null) {
                document.getElementById("node" + $scope.nowClick).style.color = "black";
            }
            $scope.showSign=false;
            $scope.showProperty=false;
            $scope.showEntry=false;
            $scope.showNone=true;
            $scope.showAllCondition=false;
            $scope.showMethod=false;
        }

        $scope.addConditionRow=function(){
            init();
            var count=$scope.count++;
            var rowC = document.getElementsByName("rowC");
            if(rowC.length==0) {
                angular.element("#condition").append(
                    $compile(
                        "<div class='entry-set' name='rowC' id='remove" + count + "'>" +
                        "<div class='entry-set-l' id='addRow" + count + "'>" +
                        "</div>" +
                        "<div class='entry-set-r'>" +
                        "<span><a href ng-click='addCondition(" + count + ")'>()</a></span>" +
                        "<span><a href ng-click='removeCondition()' ng-dblclick='removeRowCondition(" + count + ")'>&nbsp;-</a></span>" +
                        "</div>" +
                        "</div>"
                    )($scope)
                )
            }else{
                angular.element("#condition").append(
                    $compile(
                        "<div class='entry-set' name='rowC' id='remove" + count + "'>" +
                        "<div class='entry-set-l' id='addRow" + count + "'>" +
                        "<span class='also'><a href='#' ng-click='change("+count+")' name='node'  id='symbol"+count+"' value='{&apos;oper&apos;:&apos;&&&apos;}'>并且</a></span>"+
                        "</div>" +
                        "<div class='entry-set-r'>" +
                        "<span><a href ng-click='addCondition(" + count + ")'>()</a></span>" +
                        "<span><a href ng-click='removeCondition()' ng-dblclick='removeRowCondition(" + count + ")'>&nbsp;-</a></span>" +
                        "</div>" +
                        "</div>"
                    )($scope)
                )
            }
        };

        $scope.change=function (click){
            if(angular.element("#symbol"+click).text()=="或者"){
                angular.element("#symbol"+click).text("并且");

                angular.element("#symbol"+click).attr("value","{'oper':'&&'}");
            }else if(angular.element("#symbol"+click).text()=="并且"){
                angular.element("#symbol"+click).text("或者");
                angular.element("#symbol"+click).attr("value","{'oper':'||'}");
            }

        }

        $scope.addThen=function(){
            var count=$scope.count++;
            angular.element("#then").append(
                $compile(
                    "<div class='entry-set' name='rowC' id='remove" + count + "'>" +
                    "<div class='entry-set-l' id='addRow" + count + "'>" +
                        "<span class='also'><a href='#' name='node' id  = 'then"+count+"' ng-click='changeThen("+count+")' value='{&apos;type&apos;:&apos;setRtnValue&apos;}' >返回：</a></span>"+
                    "</div>"+
                    "<div class='entry-set-r'>"+
                    "<span><a href ng-click='addCondition(" + count + ")'>()</a></span>" +
                    "<span><a href ng-click='removeCondition()' ng-dblclick='removeRowCondition(" + count + ")'>&nbsp;-</a></span>" +
                    "</div>"+
                    "</div>"
                )($scope)
            );
        }

        $scope.changeThen=function(click){
            if(angular.element("#then"+click).text()=="返回："){
                angular.element("#then"+click).text("临时变量：");
                angular.element("#then"+click).attr("value","{'type':'setVariable'}");
            }else if(angular.element("#then"+click).text()=="临时变量："){
                angular.element("#then"+click).text("返回：");
                angular.element("#then"+click).attr("value","{'type':'setRtnValue'}");
            }
        }


        $scope.addCondition=function(count){
            init();
            // var count=$scope.count-1;
            var button= document.getElementsByName("addButton");
            if(button.length==0) {
                angular.element("#addRow" + count).append(
                    $compile(
                        "<span  id='click"+$scope.countCondition+"'><button type='button' name ='addButton' id='showCondition"+count+"' ng-click='show("+$scope.countCondition+",&apos;button&apos;)' class='engine-btn-default'>点击选择</button></span>"
                    )($scope)
                );
                $scope.countCondition++;
            }
        };

        $scope.removeCondition = function(){
            angular.element("#click" + $scope.nowClick).remove();
        };

        $scope.removeRowCondition=function(count){
            angular.element("#remove" + count).remove();
            $scope.count--;
            init();
        };

        $scope.show=function(type,model){
            var node = document.getElementsByName("node");
            for(var i=0;i<node.length;i++){
                node[i].style.color="black";
            }
            var list = document.getElementsByName("column");
            for(var i=0; i< list.length; i++){
                list[i].className = "";
            }
            if(type=='sign'){
                document.getElementById(type).setAttribute("class","on");
                if( document.getElementById("node" + $scope.nowClick)!=null) {
                    document.getElementById("node" + $scope.nowClick).style.color = "red";
                }
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=false;
                $scope.showSign=true;
                $scope.showEntry=false;
                $scope.showVariable=false;
                $scope.showMethod=false;
            }else if(type=='entry'){
                document.getElementById(type).setAttribute("class","on");
                if( document.getElementById("node" + $scope.nowClick)!=null) {
                    document.getElementById("node" + $scope.nowClick).style.color = "red";
                }
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=false;
                $scope.showSign=false;
                $scope.showEntry=true;
                $scope.showVariable=false;
                $scope.showMethod=false;
            }else if(type=='property'){
                document.getElementById(type).setAttribute("class","on");
                if( document.getElementById("node" + $scope.nowClick)!=null) {
                    document.getElementById("node" + $scope.nowClick).style.color = "red";
                }
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=true;
                $scope.showSign=false;
                $scope.showEntry=false;
                $scope.showVariable=false;
                $scope.showMethod=false;
            }else if (type=='variable'){
                document.getElementById(type).setAttribute("class","on");
                if( document.getElementById("node" + $scope.nowClick)!=null) {
                    document.getElementById("node" + $scope.nowClick).style.color = "red";
                }
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=false;
                $scope.showSign=false;
                $scope.showEntry=false;
                $scope.showVariable=true;
                $scope.showMethod=false;
            }else if (type=='method'){
                document.getElementById(type).setAttribute("class","on");
                if( document.getElementById("node" + $scope.nowClick)!=null) {
                    document.getElementById("node" + $scope.nowClick).style.color = "red";
                }
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=false;
                $scope.showSign=false;
                $scope.showEntry=false;
                $scope.showVariable=false;
                $scope.showMethod=true;
            }else{
                $scope.nowClick = type;
                if(model=="button") {
                    // document.getElementById("showCondition" + ($scope.count - 1)).style.backgroundColor = "red";
                }else if(model=="node"){
                    document.getElementById("node" + $scope.nowClick).style.color="red";
                }

                //document.getElementById('show'+$scope.nowClick).style.color="red";
                document.getElementById('property').setAttribute("class","on");
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=true;
                $scope.showSign=false;
                $scope.showEntry=false;
                $scope.showVariable=false;
                $scope.showMethod=false;
            }
        };

        $scope.viewObject = function (id,margin) {
            if($("#"+id).text()=="对象[-]"){
                angular.element("#son"+id).text("");
                $("#"+id).text("对象[+]");
                return;
            }
            $("#"+id).text("对象[-]");
            childAttributeResource.get({
                id: id
            }, function (response) {
                if (response.success) {
                    var records = response.data;
                    angular.forEach(records, function (item){
                        if(item.dataType!='Object'){
                            angular.element("#son"+id).append(
                                $compile(
                                    "<div class='model-value model-value-son' style='margin-left:"+20*margin+"px'>"+
                                    "<div class='model-value-l'><button type='button' class='engine-btn-model' ng-click='addModel(&apos;"+item.name+"&apos;)'>"+item.dataType+"</button></div>"+
                                    "<div class='model-value-r'>"+item.name+"</div>"+
                                    "<div class='clear'></div>"+
                                    "</div>"
                                )($scope)
                            )
                        }else{
                            angular.element("#son"+id).append(
                                $compile(
                                    "<div class='model-value model-value-son' style='margin-left:"+20*margin+"px'>"+
                                    "<div class='model-value-l'><button type='button' id='"+item.id+"' ng-click='viewObject(&apos;"+item.id+"&apos;,"+(margin+1)+")' class='engine-btn-model'>对象[+]</button></div>"+
                                    "<div class='model-value-r'>"+item.name+"</div>"+
                                    "<div class='clear'></div>"+
                                    "</div>"+
                                    "<div id='son"+item.id+"'></div>"
                                )($scope)
                            )
                        }
                    })
                }
            });
        };


        $scope.addEntry=function(){
            document.getElementById('click'+$scope.nowClick).setAttribute("class","attribute");
            angular.element("#click" + $scope.nowClick).html(
                $compile(
                    "<a href='#' name='node' id='node"+$scope.nowClick+"' ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;)'  ng-dblclick='addFront(&apos;"+$scope.nowClick+"&apos;)'   value='{&apos;type&apos;:&apos;const&apos;,&apos;value&apos;:&apos;"+$scope.textEntry+"&apos;}'>"+$scope.textEntry+"</a>"
                )($scope)
            );
        };
        $scope.addSign=function(value){
            document.getElementById('click'+$scope.nowClick).setAttribute("class","attribute");
            angular.element("#click" + $scope.nowClick).html(
                $compile(
                    "<a href='#' name='node'  id='node"+$scope.nowClick+"'  ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;)'  ng-dblclick='addFront(&apos;"+$scope.nowClick+"&apos;)'    value='{&apos;oper&apos;:&apos;"+value+"&apos;}'>"+value+"</a>"
                )($scope)
            )
        };
        $scope.addModel=function(value){
            document.getElementById('click'+$scope.nowClick).setAttribute("class","attribute");
            angular.element("#click" + $scope.nowClick).html(
                $compile(
                    "<a href='#' name='node'  id='node"+$scope.nowClick+"'  ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;)'   ng-dblclick='addFront(&apos;"+$scope.nowClick+"&apos;)'   value='{&apos;type&apos;:&apos;model&apos;,&apos;value&apos;:&apos;"+value+"&apos;}'>"+value+"</a>"
                )($scope)
            )
        };

        $scope.addVariable=function(value){
            document.getElementById('click'+$scope.nowClick).setAttribute("class","attribute");
            angular.element("#click" + $scope.nowClick).html(
                $compile(
                    "<a href='#' name='node'  id='node"+$scope.nowClick+"'  ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;)'   ng-dblclick='addFront(&apos;"+$scope.nowClick+"&apos;)'   value='{&apos;type&apos;:&apos;variable&apos;,&apos;variableName&apos;:&apos;"+value+"&apos;}'>"+value+"</a>"
                )($scope)
            )
        };

        $scope.addMethod=function(value,text){
            if(value=='addHours') {
                var hour = document.getElementById("addHours").value;
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='#' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;)'   ng-dblclick='addFront(&apos;" + $scope.nowClick + "&apos;)'   value='{&apos;type&apos;:&apos;"+value+"&apos;,&apos;source&apos;:&apos;{}&apos;,&apos;hour&apos;:&apos;" + hour + "&apos;}'>加" + hour + "小时</a>"
                    )($scope)
                )
            }else if(value=='lastDateTime'){
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='#' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;)'   ng-dblclick='addFront(&apos;" + $scope.nowClick + "&apos;)'   value='{&apos;type&apos;:&apos;"+value+"&apos;,&apos;source&apos;:&apos;{}&apos;}'>"+text+"</a>"
                    )($scope)
                )
            }else if(value=='nowDate'){
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='#' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;)'   ng-dblclick='addFront(&apos;" + $scope.nowClick + "&apos;)'   value='{&apos;type&apos;:&apos;"+value+"&apos;}'>"+text+"</a>"
                    )($scope)
                )
            }else if(value =="setKey"){
                var key = document.getElementById("setKey").value;
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='#' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;)'   ng-dblclick='addFront(&apos;" + $scope.nowClick + "&apos;)'   value='{&apos;key&apos;:&apos;"+key+"&apos;}'>KEY："+key+"</a>"
                    )($scope)
                )
            }
        };

        $scope.addFront=function(value){
            init();
            var count=$scope.count-1;
            var button= document.getElementById("showCondition"+count);
            if(button==null||button==undefined) {
                angular.element("#click" + value).before(
                    $compile(
                        "<span id='click" + $scope.countCondition + "'><button type='button' id='showCondition" + count + "' ng-click='show(" + $scope.countCondition + ")' class='engine-btn-default'>点击选择</button></span>"
                    )($scope)
                )
            }
            $scope.countCondition++;
        }

        $scope.save=function(){
            var list=[];
            var nodes = $("a[name='node']");
            angular.forEach(nodes,function(node){
                list.push( eval("(" + node.attributes.value.nodeValue + ")"));
            });
            var conditionList = [];
            var resultList=[];
            for(var i=0;i<list.length;i++){
                if(list[i].type=="setVariable"||list[i].type=="setRtnValue"){
                    conditionList = list.slice(0,i);
                    resultList = list.slice(i,list.length);
                    break;
                }
            }

            var condition = getCondition(conditionList);//条件
            var result = getResult(resultList);
            var rule={};
            var expression ={"if":{"condition":{},"then":[]}};
            expression.if.condition = condition;
            expression.if.then=result;
            rule.id= $scope.id;
            rule.expression= JSON.stringify(expression);
            ruleResource.update(rule, function (response) {
                if(response.success){
                    alert("修改成功！");
                }
            });
        };

        function getCondition(list){
            var resultList=[];
            resultList = handleParenthesis(list);
            resultList = outParenthesis(resultList);
            return resultList;
        }

        function getResult(resultlList){
            var list =[];
            var thenList = [];

            var flag=0;
            for(var i=1;i<resultlList.length;i++){
                if(resultlList[i].type=="setVariable"||resultlList[i].type=="setRtnValue"){
                    list.push(resultlList.slice(flag,i));
                    flag=i;
                }
                if(i==resultlList.length-1){
                    list.push(resultlList.slice(flag,resultlList.length));
                }
            }
            for(var i=0;i<list.length;i++){
                var list0=list[i];
                var list1=[];

                var model={};
                model.type = list0[0].type;
                if(model.type=='setVariable'){
                    model.key = list0[1].key;//设置临时变量时使用
                    list1=handleParenthesis(list0.slice(2,list0.length));
                    list1=outParenthesis(list1);
                }else if(model.type=='setRtnValue'){
                    list1=handleParenthesis(list0.slice(1,list0.length));
                    list1=outParenthesis(list1);
                }
                model.value =list1;
                thenList.push(model);
            }
            return thenList;
        }

        function handleParenthesis(list){
            var result=[];
            var resultList=[];
            var leftBrackets =[];
            var brackets=[];
            for(var i=0;i<list.length;i++){
                if(list[i].oper!=null&&list[i].oper=="("){
                    leftBrackets.push(i);
                }else if(list[i].oper!=null&&list[i].oper==")"){
                    var model = {};
                    model.left = leftBrackets.pop();
                    model.right = i;
                    brackets.push(model);
                }
            }
            if(brackets.length>0) {
                for (var i = 0; i < list.length; i++) {
                    if (i >= brackets[0].left && i <= brackets[0].right) {
                        i = brackets[0].right+1;
                        resultList.push(setParenthesis(list.slice(brackets[0].left+1, brackets[0].right)));
                    }
                    if(i<list.length) {
                        resultList.push(list[i]);
                    }
                }
                return handleParenthesis(resultList)
            }
            return list;
        }


        function setParenthesis(list){
            var result ={"type":"parenthesis","expression":{}};
            result.expression=outParenthesis(list);
            return result;
        }

        function outParenthesis(list){
            var methodList=[];
            var list1=[];
            var list2=[];
            var list3=[];
            var list4=[];

            for(var i=0;i<list.length;i++){
                var model = {};
                if(list[i].type=='lastDateTime'||list[i].type=='addHours'){
                    // model.type =list[i].type;
                    model=list[i];
                    model.source=list[i-1];
                    methodList.pop();
                    methodList.push(model);
                    list[i-1]=model;
                }else {
                    methodList.push(list[i]);
                }
            }
            for(var i=0;i<methodList.length;i++){
                var model = {'oper':{},'left':{'type':'','value':''},'right':{'type':'','value':''}};
                if(methodList[i].oper!=null&&(methodList[i].oper=="*"||methodList[i].oper=="/")){
                    model.oper=methodList[i].oper;
                    model.left=methodList[i-1];
                    model.right=methodList[i+1];
                    list1.pop();
                    list1.push(model);
                    methodList[i-1]=model;
                    methodList[i+1]=model;
                    i++;
                }else{
                    list1.push(methodList[i]);
                }
            }

            for(var i=0;i<list1.length;i++){
                var model = {'oper':{},'left':{'type':'','value':''},'right':{'type':'','value':''}};
                if(list1[i].oper!=null&&(list1[i].oper=="+"||list1[i].oper=="-")){
                    model.oper=list1[i].oper;
                    model.left=list1[i-1];
                    model.right=list1[i+1];
                    list2.pop();
                    list2.push(model);
                    list1[i-1]=model;
                    list1[i+1]=model;
                    i++;
                }else{
                    list2.push(list1[i]);
                }
            }
            for(var i=0;i<list2.length;i++){
                var model = {'oper':{},'left':{'type':'','value':''},'right':{'type':'','value':''}};
                if(list2[i].oper!=null&&(list2[i].oper=="<"||list2[i].oper==">"||list2[i].oper=="=="||list2[i].oper==">="||list2[i].oper=="<="||list2[i].oper=="!=")){
                    model.oper=list2[i].oper;
                    model.left=list2[i-1];
                    model.right=list2[i+1];
                    list3.pop();
                    list3.push(model);
                    list2[i-1]=model;
                    list2[i+1]=model;
                    i++;
                }else{
                    list3.push(list2[i]);
                }
            }
            for(var i=0;i<list3.length;i++){
                var model = {'oper':{},'left':{'type':'','value':''},'right':{'type':'','value':''}};
                if(list3[i].oper!=null&&(list3[i].oper=="&&"||list3[i].oper=="||")){
                    model.oper=list3[i].oper;
                    model.left=list3[i-1];
                    model.right=list3[i+1];
                    list4.pop();
                    list4.push(model);
                    list3[i-1]=model;
                    list3[i+1]=model;
                    i++;
                }else{
                    list4.push(list3[i]);
                }
            }
            return list4[0];
        }


    });

});